package com.vgemv.jsutilitysdk.Table.JsTableFragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.vgemv.jsutilitysdk.JsThread.JsThreadManager;
import com.vgemv.jsutilitysdk.Menu.JsMenuView.JsMenuItemVm.JsMenuItemVm;
import com.vgemv.jsutilitysdk.Menu.JsMenuView.JsMenuView;
import com.vgemv.jsutilitysdk.Menu.JsMenuView.JsMenuViewBasicCallback;
import com.vgemv.jsutilitysdk.Menu.JsMenuView.JsMenuViewRefreshCallback;
import com.vgemv.jsutilitysdk.Menu.JsMenuView.JsMenuViewTouchThroughCallback;

import java.util.ArrayList;

public class JsTableFragment extends Fragment  {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";



    // private ArrayList<JsMenuCellVm> mal_cells;
    private ArrayList<JsMenuItemVm> mal_vms;

    public JsMenuViewBasicCallback mBasicCallback;
    public JsMenuViewRefreshCallback mRefreshCallback;
    public JsMenuViewTouchThroughCallback mTouchThroughCallback;


    public JsMenuView mMenuView;

    private int setupUiCount = 0;

    public JsTableFragment() {
        super();
        //此时没有Context,无法创建view.不能在这里setupUi.
    }

    public void setupUiIfNeeded() {
        setupUiCount ++;
        if(setupUiCount == 1) {
            JsThreadManager.runInMainThreadAtNextRunloop(
                    new Runnable() {
                        @Override
                        public void run() {
                            setupUi();
                            setupUiCount = 0;
                        }
                    }
            );
        }

    }

    /*
    根据vm,安装和显示.
     */
    private void setupUi() {

//        Context context = getContext();
//
//        //可以设置fragment的大小,从导航栏下面开始.
//        {
//            if(mll_root == null) {
//                mll_root = new SmartRefreshLayout(getContext());
//                mll_root.setId(View.generateViewId());
//                //设置大小,默认大小是WRAP_CONTENT,不能设置fragment的大小,fragment没有大小的概念.只能设置fragment的rootview的大小.
//                ViewGroup.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
//                mll_root.setLayoutParams(lp);
//
//            }
//        }
//
//        //Recyclerview
//        {
//            if (mRecyclerView == null) {
//                mRecyclerView = new JsRecyclerView(getContext());
//                mRecyclerView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
//                mll_root.addView(mRecyclerView);
//
//                {
//                    //上拉刷新 下拉加载
//                    if (mVm.mb_enableRefreshAndLoadmore) {
//                        RefreshHeader header = new ClassicsHeader(context);
//                        RefreshFooter footer = new ClassicsFooter(context);
//                        mll_root.setRefreshHeader(header);
//                        mll_root.setRefreshFooter(footer);
//                        mll_root.setOnRefreshListener(new OnRefreshListener() {
//                            @Override
//                            public void onRefresh(RefreshLayout refreshlayout) {
//                                if (mRefreshCallback != null) {
//                                    mRefreshCallback.onRefresh(JsMenuFragment.this);
//                                }
//                            }
//                        });
//                        mll_root.setOnLoadMoreListener(new OnLoadMoreListener() {
//                            @Override
//                            public void onLoadMore(RefreshLayout refreshlayout) {
//                                if (mRefreshCallback != null) {
//                                    mRefreshCallback.onLoadMore(JsMenuFragment.this, 0);
//                                }
//                            }
//                        });
//                    } else {
//                        mll_root.setEnableRefresh(false);
//                        mll_root.setEnableLoadMore(false);
//                    }
//                }
//                //一次手势过程中,有可能使用两个一样的数据
//                mRecyclerView.setOnTouchListener(new View.OnTouchListener() {
//                    @Override
//                    public boolean onTouch(View view, MotionEvent motionEvent) {
////                        JsLogManager.logc_d("onTouch","event is %d",motionEvent.hashCode());
//                       if(mTouchThroughCallback != null) {
//                           //存储第一下事件
//                           if(!mb_isJustDown && motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
////                               JsLogManager.logc_d("onTouch","down");
//                               mb_isJustDown = true;
//                           }
//                           else {
//                            if(mb_isJustDown && motionEvent.getAction() == MotionEvent.ACTION_UP) {
////                                JsLogManager.logc_d("onTouch","down->up=click");
//                                //进行了一次点击
////                                mMe_first = null;
//                                return mTouchThroughCallback.jsMenuViewReceivedClickMotinEvent(motionEvent);
//                            }
//                            else {
//                                //不是点击
////                                mMe_first = null;
//                            }
//                           }
//                       }
//                       return false;
//
//                    }
//                });
//
//
//                // 设置布局方式 //网格布局
//                mLayoutManager = null;
//                switch (mVm.layoutStyle) {
//                    case 0: {
//                        GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 5);
//                        layoutManager.setOrientation(GridLayoutManager.VERTICAL);
//                        mRecyclerView.setLayoutManager(layoutManager);
//                        mLayoutManager = layoutManager;
//                        break;
//                    }
//                    case 1: {
//                        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
//                        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
//                        mRecyclerView.setLayoutManager(layoutManager);
//                        mLayoutManager = layoutManager;
//                        break;
//                    }
//                    case 2: {
//                        //竖直线性布局.
//                        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
//                        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
//                        mRecyclerView.setLayoutManager(layoutManager);
//                        mLayoutManager = layoutManager;
//                        break;
//                    }
//                    //        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(getContext(),4);
////        layoutManager.setOrientation(GridLayoutManager.VERTICAL);
////        mRecyclerView.setLayoutManager(layoutManager);
//                }
//
//
//                // 设置Item的样式
//
//                mRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
//                    @Override
//                    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
//                        Rect rect = null;
//                        int index = parent.getChildAdapterPosition(view);
//                        if (mCallback != null) {
//                            rect = mCallback.jsMenuViewSetItemOffset(JsMenuFragment.this, index);
//                        }
//
//                        if (rect != null) {
//                            outRect.top = rect.top;
//                            outRect.left = rect.left;
//                            outRect.right = rect.right;
//                            outRect.bottom = rect.bottom;
//                        } else {
//                            super.getItemOffsets(outRect, view, parent, state);
//                        }
//                        int recyclerViewHeight = parent.getHeight();
//                        //TODO: view.getHeight,有时候为0. view.getMeasuredHeight,有时候也是0
//                        // 这样就无法根据view的大小来计算相对的位置了.
//                        //                int itemViewHeight = view.getHeight();
//                        int itemViewHeight = view.getMeasuredHeight();
////                    JsLogManager.logc_d("JsRecyclerView", "recyclerViewHeight is %d,itemViewHeight is %d", recyclerViewHeight, itemViewHeight);
//                    }
//                });
//
//
//                mAdapter.mal_cellModel = mal_vms;
//                mAdapter.adapterCallback = this;
//                mRecyclerView.setAdapter(mAdapter);
//
//                //显示初始选择项,只在初始化时调用
//                if(mVm.mI_initialSelectedIndex != null &&mal_vms.size() > 0) {
//                    mi_selectedIndex = mVm.mI_initialSelectedIndex;
//                    JsMenuItemVm itemVm = mal_vms.get(mi_selectedIndex);
//                    itemVm.mb_isSelected = true;
//                }
//            }
//        }
//
//        //背景色
//        if(mVm.mColor_background != null) {
//            mRecyclerView.setBackgroundColor(mVm.mColor_background);
//        }
//        //可见性
//        mll_root.setVisibility(mVm.mi_visibility);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public ArrayList<JsMenuItemVm> vms() {
        return mal_vms;
    }

    //需要返回一个布局,作为Fragment的根视图.
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mMenuView = new JsMenuView(getContext());
        mMenuView.mBasicCallback = mBasicCallback;
        return mMenuView;
    }



    @Override
    public void onResume() {
        super.onResume();
    }


    // 2 InnnerFunction


    // 3 Interface

    /**
     * 将当前fragment的rootView添加到指定的ContainerView中.
     * 这里设置会是占满ContainerView.
     * @param activity  指定的Activity
     * @param containerView      目标ContainerView
     */
    public void moveToParentView(AppCompatActivity activity, View containerView){
        //containerView必须有id,如果没有设置.
        int id = containerView.getId();
        if(id < 0) {
            containerView.setId(View.generateViewId());
        }
        FragmentManager fragmentManager = activity.getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(containerView.getId(),this);
        fragmentTransaction.show(this);
        fragmentTransaction.commit();
    }




    // 1 更新数据
    /**
     * 1.1 全部数据刷新
     * 如果mAdapter还没初始化就要求reload,其实可以不reload.
     */
    public void reloadData() {
      mMenuView.reloadData();
    }

    /**
     * 1.2 增加数据刷新
     * @param insertedPosition      数据增加的位置.
     */
    public void  loadInsertedItem(int insertedPosition) {
        mMenuView.loadInsertedItem(insertedPosition);
    }



    // 2 上拉加载和下拉刷新
    //
    /**
     * 结束刷新
     isSuccess
     YES:
     dataCount > 0
     * 已加载页数为1
     * 结束刷新
     * 结束下拉加载且可以加载.

     dataCount = 0
     * 已加载页数为0
     * 结束刷新
     * 结束下拉加载且不可以加载.
     * 如果有EmptyView应该显示EmptyView

     NO:仅仅结束刷新,其余状态不改变
     */
    public void finishRefresh(boolean isSuccess,boolean hasData) {
        mMenuView.finishRefresh(isSuccess,hasData);
    }

    /**
     * 结束加载
     isSuccess:此次加载是否成功,如果成功
     YES:将根据dataCount设置是否还有更多的数据. 0表示没有更多数据,已加载页数不变;非0,表示还有数据,已加载页+1;
     NO:仅仅结束加载,其余状态不发生改变.
     */
    public void finishLoadMore(boolean isSuccess,boolean hasData) {
       mMenuView.finishLoadMore(isSuccess,hasData);
    }

    public void refresh() {
        mMenuView.refresh();
    }


    // 3 位置控制

    /**
     * 3.1 滚动到顶部
     *
     */
    public void scrollToTop() {
        //RecyclerView does not support scrolling to an absolute position. Use scrollToPosition instead
//        mRecyclerView.scrollTo(0,0);
        mMenuView.scrollToTop();
    }

    public void scrollToBottom() {
        mMenuView.scrollToBottom();
    }


    /**
     * 4 选择指定位置的item
     */
    public void chooseItem(int index) {
       mMenuView.chooseItem(index);
    }

    public Integer selectedIndex() {
        return mMenuView.selectedIndex();
    }

    public int loadedPage() {
        return mMenuView.loadedPage();
    }
}